package is.server.controller.session.local.command;

import is.common.exception.RowNotFoundException;
import is.common.exception.RowsAreaIncorrectException;
import is.common.interfaces.Command;
import is.server.Main;

/**
 * @author aspr0
 *         Date: 06.04.12
 *         Time: 23:07
 */
public class ListCommand implements Command
{
    private String[] request;

    public ListCommand(String[] request)
    {
        this.request = request;
    }

    public void execute()
    {
        if (request.length < 4)
        {
            Main.getController().getUserInterface().exposeErrMsg("insufficient parameters"); //todo
            return;
        }

        int sectionNum;
        int rowNumStart;
        int howMany;

        try
        {
            sectionNum = Integer.parseInt(request[1]);
            rowNumStart = Integer.parseInt(request[2]);
            howMany = Integer.parseInt(request[3]);
        }
        catch (NumberFormatException e)
        {
            Main.getController().getUserInterface().exposeErrMsg("incorrect parameters"); //todo
            return;
        }

        if (Main.getController().getModel().isActivated())
        {
            try
            {
                String[] header = Main.getController().getModel().getHeader(sectionNum);
                String[][] rows = Main.getController().getModel().getRows(sectionNum, rowNumStart, howMany);

                Main.getController().getUserInterface().exposeRows(sectionNum, header, rows);
            }
            catch (RowsAreaIncorrectException e)
            {
                Main.getController().getUserInterface().exposeErrMsg("wrong rows area specified"); //todo
//            e.printStackTrace();
            }
            catch (java.io.IOException e)
            {
                e.printStackTrace();
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (RowNotFoundException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            Main.getController().getUserInterface().exposeErrMsg("model deactivated"); //todo
        }
    }
}
